//
//  ManageReceivedAddressController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/18.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "ManageReceivedAddressController.h"
//untils
#import "UIColor+Hex.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
#import "Global.h"
//model
#import "ReceivedAddressModel.h"
#import "ReceivedAddressOBJECT.h"
//views
#import "ReceivedAddressCell.h"
//controller
#import "AddReceiveAddressController.h"
#import "SureOrderController.h"
#import "MyGoodsSureOrderController.h"
#import "EmptyPageView.h"
#import "MTA.h"
@interface ManageReceivedAddressController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIButton *_quitLoginButton;
}
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)UIButton *editbutton;
@property(nonatomic, strong)EmptyPageView *emptyPageView;
@end

@implementation ManageReceivedAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    _dataSource = [[NSMutableArray alloc]init];
    self.title = @"我的收货地址";
    //[self addRightNavItemWithTitle:@"编辑"];
    [self addBackNavItem];
    [self setupSubView];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadReceivedAddressList];

    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"我的收货地址"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"我的收货地址"];
}
#pragma mark -- request Data
//修改收货地址
- (void)setDefaultAddressWithData:(ReceivedAddressOBJECT*)data {
    /*SIGNATURE:设备识别码
     TOKEN:用户签名
     LINKNAME:昵称
     TEL:联系电话，座机或手机
     SEX:性别1：男，2：女
     COMMUNITYID:社区ID
     BUILDID: 楼号ID
     UNITID:单元号ID
     ROOMID:房间门牌号ID
     ISDEFAULT:是否默认 1：是，0：否
     */
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    UserInfoModel *userModel =[[ManagerGlobeUntil sharedManager] getUserInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:model.storeID forKey:@"STOREID"];
    [parameter setObject:userModel.token forKey:@"TOKEN"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    [parameter setObject:[NSNumber numberWithDouble:data.iDProperty] forKey:@"ADDRESSID"];
    [parameter setObject:[NSNumber numberWithDouble:data.sEX] forKey:@"SEX"];
    [parameter setObject:[NSString stringISNull:data.lINKNAME] forKey:@"LINKNAME"];
    [parameter setObject:[NSString stringISNull:data.tEL] forKey:@"TEL"];
    [parameter setObject:[NSNumber numberWithInteger:1] forKey:@"ISDEFAULT"];
    [parameter setObject:data.aDDRESS forKey:@"ADDRESS"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"user/updateAddress" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            ReceivedAddressModel *model = [ReceivedAddressModel modelObjectWithDictionary:responseObject];
            NSString *state = [NSString stringTransformObject:model.sTATE];//状态码
            [weakSelf.dataSource removeAllObjects];
            if ([state isEqualToString:@"0"]) {//请求成功
                [weakSelf.dataSource addObjectsFromArray:model.oBJECT];
            }else {//请求失败
                //[[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
            
            [weakSelf.tableView reloadData];
        }
    } failure:^(bool isFailure) {
        
        
    }];
    
}
//查询收货地址列表
- (void)loadReceivedAddressList {
  //    SIGNATURE			设备识别码
  //    TOKEN			用户签名
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:model.token forKey:@"TOKEN"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"user/addressList" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            ReceivedAddressModel *model = [ReceivedAddressModel modelObjectWithDictionary:responseObject];
            NSString *msg = model.mSG;
            NSString *state = [NSString stringTransformObject:model.sTATE];//状态码
            [weakSelf.dataSource removeAllObjects];
            if ([state isEqualToString:@"0"]) {//请求成功
                [weakSelf.dataSource addObjectsFromArray:model.oBJECT];
                
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:self.view];
            }
            
            if (weakSelf.dataSource.count == 0) {
                weakSelf.emptyPageView.hidden = NO;
                weakSelf.view.backgroundColor =[UIColor whiteColor];
                
            } else {
                weakSelf.emptyPageView.hidden = YES;
                weakSelf.view.backgroundColor =[UIColor colorWithHexString:@"#efefef"];
                [weakSelf updateDataSource];
            }
            [weakSelf.tableView reloadData];
        }
    } failure:^(bool isFailure) {
        
         [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
    }];

}
//删除收货地址
- (void)loadRemoveReceivedAddressDatasWithdata:(ReceivedAddressOBJECT *)data
{
    /*SIGNATURE:设备识别码
     TOKEN:用户签名
     ADDRESSID:收货地址ID
     */
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:model.token forKey:@"TOKEN"];
    [parameter setObject:[NSString stringWithFormat:@"%f",data.iDProperty] forKey:@"ADDRESSID"];
     __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"user/delAddress" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                //            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"删除成功" inView:self.view];
                [weakSelf loadReceivedAddressList];
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }

        }
        
    } failure:^(bool isFailure) {
        
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
    }];
}
//更新数据源，把默认的收货地址放到第一位
- (void)updateDataSource {
    if (self.dataSource.count > 1) {//多个地址把默认地址放到最上面
        NSMutableArray *copyarr = [self.dataSource mutableCopy];
        for (ReceivedAddressOBJECT *data in copyarr) {
            if (data.iSDEFAULT == 1) {//默认地址
                [self.dataSource removeObject:data];
                [self.dataSource insertObject:data atIndex:0];
                break ;
            }
        }
        [self.tableView reloadData];
    } else if(self.dataSource.count == 1) {//如果只有一个地址默认就是默认地址
        ReceivedAddressOBJECT *data = [self.dataSource firstObject];
        if (data.iSDEFAULT != 1) {//不是默认地址
            [self setDefaultAddressWithData:data];
        } else {
            [self.tableView reloadData];
        }
    } else if(self.dataSource.count == 0) {
       [self.tableView reloadData];
    }

}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {//默认地址cell样式
        static NSString *cellIdentifier1 = @"cellIdentifier1";
        ReceivedAddressCell *cell1 = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
        if (cell1 == nil) {
            cell1 = [[ReceivedAddressCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier1];
            cell1.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
//            cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        ReceivedAddressOBJECT *data = [self.dataSource objectAtIndex:indexPath.row];
        NSString *address = [NSString stringWithFormat:@"%@",[NSString stringTransformObject:data.aDDRESS]];
       
        cell1.itemIndexPath = indexPath;
        cell1.delegate = (id<ReceivedAddressCellDelegate>)self;
        [cell1 updataWithName:[NSString stringTransformObject:data.lINKNAME] telNumber:[NSString stringTransformObject:data.tEL] address:address];
        return cell1;
    }
    static NSString *cellIdentifier = @"cellIdentifier";
    ReceivedAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ReceivedAddressCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
   ReceivedAddressOBJECT *data = [self.dataSource objectAtIndex:indexPath.row];
     NSString *address = [NSString stringWithFormat:@"%@",[NSString stringTransformObject:data.aDDRESS]];
    cell.itemIndexPath = indexPath;
    cell.delegate = (id<ReceivedAddressCellDelegate>)self;
    [cell updataWithName:[NSString stringTransformObject:data.lINKNAME] telNumber:[NSString stringTransformObject:data.tEL] address:address];
    return cell;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource.count - 1 == indexPath.row) {
        return HightScalar(72);
    }
    return HightScalar(80);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.supperControllerType == kUserCenterPushToAddReceiveAddressController) {//从个人中心
        if (!self.tableView.editing) {
            AddReceiveAddressController *addVC = [[AddReceiveAddressController alloc]init];
            addVC.editAddressType = kmodifyReceiveAddressType;
            addVC.receivedAddressDatas = [self.dataSource objectAtIndex:indexPath.row];
            addVC.supperControllerType = kUserCenterPushToAddReceiveAddressController;
            [self.navigationController pushViewController:addVC animated:YES];
        }
        
    } else if (self.supperControllerType == kSureOrderPushToAddReceiveAddressController) {//从确认订单页面跳转
        for (UIViewController*VC in self.navigationController.childViewControllers) {
            if ([VC isKindOfClass:[SureOrderController class]]) {
                ReceivedAddressOBJECT *data = [self.dataSource objectAtIndex:indexPath.row];
                ((SureOrderController*)VC).addressData = data;
                [self.navigationController popViewControllerAnimated:YES];
            } else if ([VC isKindOfClass:[MyGoodsSureOrderController class]]) {
                ReceivedAddressOBJECT *data = [self.dataSource objectAtIndex:indexPath.row];
                ((MyGoodsSureOrderController*)VC).addressData = data;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}
//侧滑删除
-(nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        
        ReceivedAddressOBJECT *data = [self.dataSource objectAtIndex:indexPath.row];
        [self loadRemoveReceivedAddressDatasWithdata:data];
    }
  

    
}
#pragma mark -- ReceivedAddressCellDelegate
- (void)selectedReceivedAddressWithItemIndex:(NSInteger)index {
    if (!self.tableView.editing) {
        AddReceiveAddressController *addVC = [[AddReceiveAddressController alloc]init];
        addVC.editAddressType = kmodifyReceiveAddressType;
        addVC.receivedAddressDatas = [self.dataSource objectAtIndex:index];
        if (self.supperControllerType == kUserCenterPushToManageReceivedAddressController) {
            addVC.supperControllerType = kUserCenterPushToAddReceiveAddressController;
        } else if (self.supperControllerType == kSureOrderPushToManageReceivedAddressController) {
            addVC.supperControllerType = kSureOrderPushToAddReceiveAddressController;
        }
        [self.navigationController pushViewController:addVC animated:YES];
    }
}
#pragma mark -- button Action
- (void)addReceivedAddressEvent {
    if ([_quitLoginButton.titleLabel.text isEqualToString:@"删除收货地址"]) {
        [self removeReceiveAddresss];
    } else if ([_quitLoginButton.titleLabel.text isEqualToString:@"新增收货地址"]) {
        AddReceiveAddressController *addVC = [[AddReceiveAddressController alloc]init];
        addVC.editAddressType = kaddReceiveAddressType;
        if (self.supperControllerType == kUserCenterPushToManageReceivedAddressController) {
            addVC.supperControllerType = kUserCenterPushToAddReceiveAddressController;
        } else if (self.supperControllerType == kSureOrderPushToManageReceivedAddressController) {
            addVC.supperControllerType = kSureOrderPushToAddReceiveAddressController;
        }
        [self.navigationController pushViewController:addVC animated:YES];
    }
}

- (void)removeReceiveAddresss {
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
    if (selectedRows.count > 0) {
        NSMutableIndexSet *indicesOfItemsToDelete = [NSMutableIndexSet new];
        for (NSIndexPath *selectionIndex in selectedRows)
        {
            [indicesOfItemsToDelete addIndex:selectionIndex.row];
        }
        // Delete the objects from our data model.
        [self.dataSource removeObjectsAtIndexes:indicesOfItemsToDelete];
        
        // Tell the tableView that we deleted the objects
        [self.tableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView setEditing:NO animated:YES];
        
    }
    if (self.dataSource.count != 0) {
        [self.tableView setEditing:YES animated:NO];
    } else {
        [_quitLoginButton setTitle:@"新增收货地址" forState:UIControlStateNormal];
        [self.editbutton setTitle:@"编辑" forState:UIControlStateNormal];
        self.editbutton.enabled = NO;
    }
    
}

- (void)rigthBtnAction:(id)sender {
    UIButton *button = (UIButton*)sender;
    self.editbutton = button;
    button.selected = !button.selected;
    [ button setTitle:button.selected ? @"完成" : @"编辑" forState:UIControlStateNormal];
    [_quitLoginButton setTitle:button.selected ? @"删除收货地址" : @"新增收货地址" forState:UIControlStateNormal];
    [self.tableView setEditing:button.selected animated:YES];
    
}
- (void)backBtnAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- 初始化视图
- (void)setupSubView {
    
    _quitLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_quitLoginButton setTitle:@"新增收货地址" forState:UIControlStateNormal];
    _quitLoginButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(17)];
    [_quitLoginButton.layer setMasksToBounds:YES];
    [_quitLoginButton.layer setCornerRadius:4];
    _quitLoginButton.frame = CGRectMake(15, CGRectGetMaxY(self.view.frame) - HightScalar(55) - 64-10, self.view.bounds.size.width - 30, HightScalar(55));
    UIImage *loginImage = [UIImage imageNamed:@"login_Btn"];
    loginImage = [loginImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
    
    [_quitLoginButton setBackgroundImage:loginImage forState:UIControlStateNormal];
    [_quitLoginButton addTarget:self action:@selector(addReceivedAddressEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_quitLoginButton];
    //无地址显示视图
    _emptyPageView = [[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 64 - HightScalar(55)-10) EmptyPageViewType:kManageReceivedAddress];
     self.emptyPageView.hidden = YES;
    _emptyPageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_emptyPageView];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)
                                                              , CGRectGetHeight(self.view.bounds) - 64 - 64)
                                             style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.allowsMultipleSelectionDuringEditing = YES;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
